package main
{
	import com.darwin.darwinNet.Net;
	import com.darwin.darwinNet.events.NetErrorEvent;
	
	import flash.events.Event;

	/**
	 * 游戏通讯类，负责管理和后台的通讯
	 * @author Roland
	 * 
	 */
	public class AppNet
	{
		public function AppNet()
		{
			if(_instance == null){
				_instance = this;
				initAppNet();
			}
			else{throw new Error("实例化单例类出错-AppNet");}
		}
		
		private function initAppNet():void
		{
			net.protocol = Net.PROTOCOL_SOCKET;
			net.cmdAdapter = new AppNetAdapter();
			
			net.addEventListener(NetErrorEvent.NET_IOERROR,onError);
			net.addEventListener(NetErrorEvent.NET_ERROR,onError);
			net.addEventListener(NetErrorEvent.TIMEOUT_ERROR,onError);

		}
		
		protected function onError(event:NetErrorEvent):void
		{
			trace("########","通讯错误","#########");
			trace("错误类型:",event.type,"\n错误代码:",event.errorCode,"\n错误信息:",event.errorMsg);
			trace("########################");
		}
		
		private static var _instance:AppNet;
		public static function getInstance():AppNet
		{
			if(_instance == null)
			{
				_instance = new AppNet;
			}
			return _instance;
		}
		
		/**
		 *	和服务器端建立socket连接 
		 * @param host
		 * @param port
		 * 
		 */
		public function connect(host:String,port:String):void
		{
			net.connect(host,port);
		}
		
		/**
		 *	请求登录socket服务器 
		 * @param uid 
		 * @param session_key
		 * 
		 */
		public function login(uid:String,session_key:String):void
		{
			net.send("1",{method:"login",uid:uid,session_key:session_key},null,Net.PROTOCOL_SOCKET);
		}
		
		/**
		 *	向socket服务器发送请求 
		 * @param cmd
		 * @param data
		 * 
		 */
		public function send(cmd:String,data:Object):void
		{
			var sendData:Object = data;
			sendData.method = cmd;
			net.send("2",sendData,null,Net.PROTOCOL_SOCKET);
		}
		
		private function get net():Net
		{
			return Net.getInstance();
		}
	}
}